package com.example.demo.bis.websocket.service.impl;

import com.example.demo.bis.websocket.service.WebSocketService;
import com.example.demo.demos.websocket.AuthWebSocketHandler;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lyh
 * @date 2025/7/22 16:14
 */
@Service
public class WebSocketServiceImpl implements WebSocketService {

    @Resource
    private AuthWebSocketHandler webSocketHandler;
    @Resource
    private ObjectMapper objectMapper;

    /**
     * 获取所有已连接客户端的IP地址
     *
     * @return IP地址列表（可能包含重复）
     */
    @Override
    public List<String> getAllConnectedClientIps() {
        return webSocketHandler.getAllClientIps();
    }

    /**
     * 向所有连接的客户端广播消息
     *
     * @param messageType 消息类型标识（前端用于区分消息类型）
     * @param payload     消息内容（任意可序列化对象）
     */
    @Override
    public void broadcastToAll(String messageType, Object payload) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", messageType);
            message.put("data", payload);
            String jsonMessage = objectMapper.writeValueAsString(message);
            webSocketHandler.broadcastMessage(jsonMessage);
        } catch (JsonProcessingException e) {
            // 处理序列化异常
            System.err.println("消息序列化失败: " + e.getMessage());
        }
    }

    /**
     * 向指定会话发送消息
     *
     * @param sessionId   目标会话ID
     * @param messageType 消息类型标识
     * @param payload     消息内容
     * @return 发送成功返回true，失败返回false
     */
    @Override
    public boolean sendToSession(String sessionId, String messageType, Object payload) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", messageType);
            message.put("data", payload);
            String jsonMessage = objectMapper.writeValueAsString(message);
            return webSocketHandler.sendToSession(sessionId, jsonMessage);
        } catch (JsonProcessingException e) {
            System.err.println("定向消息序列化失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 发送系统通知给所有客户端
     *
     * @param title   通知标题
     * @param content 通知内容
     */
    @Override
    public void sendSystemNotification(String title, String content) {
        Map<String, String> notification = new HashMap<>();
        notification.put("title", title);
        notification.put("content", content);
        broadcastToAll("SYSTEM_NOTIFICATION", notification);
    }

    /**
     * 向指定IP列表的客户端发送消息
     *
     * @param ips         目标IP地址列表
     * @param messageType 消息类型标识
     * @param payload     消息内容
     */
    @Override
    public void sendToIps(List<String> ips, String messageType, Object payload) {
        try {
            Map<String, Object> message = new HashMap<>();
            message.put("type", messageType);
            message.put("data", payload);
            String jsonMessage = objectMapper.writeValueAsString(message);

            // 委托给WebSocketHandler执行IP过滤发送
            webSocketHandler.sendToIps(ips, jsonMessage);
        } catch (JsonProcessingException e) {
            System.err.println("IP定向消息序列化失败: " + e.getMessage());
        }
    }
}
